<?php

namespace App\Service\ObjectStorage;

use App\Utils\Helper\GetterHelper;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

/**
 * 七牛云对象存储kodo服务类
 * Class QiniuCloudKodoService
 * @package App\Service\ObjectStorage
 */
class QiniuCloudKodoService extends ObjectStorageService implements ObjectStorageInterface {
    protected $bucket;
    protected $access_key;
    protected $secret_key;
    protected $upload_manager;
    protected $token;

    public function __construct () {
        $this->bucket = GetterHelper::getParameter('qiniu.kodo.bucket');
        $this->access_key = GetterHelper::getParameter('qiniu.kodo.access.key');
        $this->secret_key = GetterHelper::getParameter('qiniu.kodo.secret.key');
        $this->init();
    }

    /**
     * 初始化
     */
    public function init () {
        $this->upload_manager = new UploadManager();
        $auth = new Auth($this->access_key, $this->secret_key);
        $this->token = $auth->uploadToken($this->bucket);
    }

    /**
     * 图片上传 - 表单
     * @param $file
     * @param $file_path
     * @param string[] $allow_type
     * @param int $max_size 默认上传大小为1M
     * @return mixed
     * @throws \Exception
     */
    public function uploadFileByFromFile ($file, $file_path, $allow_type = ['jpg', 'png', 'jpeg'], $max_size = 1048576) {
        try {
            $result = [];
            // 文件校验
            $file = $this->verifyFile($file, $file_path, $allow_type, $max_size);
            // 上传到KODO
            [$response, $error] = $this->upload_manager->putFile($this->token, $file->getNewFilePath(), $file->getFileTmpName());
            if (!$error) {
                $result['key'] = $response['key'] ?? '';
            }
            return $result;
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }
}